using DynamicModelDemo.EntityFramework;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Serilog;
using Serilog.Events;
using System;
using System.Linq;
using System.Reflection;

namespace DynamicModelDemo
{
    class Program
    {
        static int Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .Enrich.FromLogContext()
                .WriteTo.Async(c => c.Console())
                .CreateLogger();
            try
            {
                Log.Information($"Starting {Assembly.GetExecutingAssembly().GetName().Name}.");
                CreateHostBuilder(args).Build().Run();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly!");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        private static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config
                       .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                       .AddJsonFile("App.json", true, true)
                       .AddJsonFile($"App.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                       .AddEnvironmentVariables()
                       ;
                })
                .ConfigureServices(services=> {
                    services.AddDbContext<MyDbContext>();
                    services.AddEntityFrameworkSqlServer();
                    services.AddHostedService<InitDbTableService>();
                    services.AddHostedService<TestHostService>();
                })
                //.UseAutofac()
                .UseSerilog();
        }


    }
}
